﻿using Blog.Core.DTO.ViewModel.User;
using Blog.Core.IServices.IUser;
using Blog.Core.Services.User;
using Newtonsoft.Json;

namespace Blog.Core.Api.HostedService
{
    /// <summary>
    /// 定时服务
    /// </summary>
    public class TimedHostedService: BackgroundService
    {
        private readonly IUserService userService;
        public TimedHostedService(IUserService userService)
        {
            this.userService = userService;
        }
        private Timer _timer; //定时器
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken
        stoppingToken)
        {
            
            //定时器创建后马上执行DoWork方法，每10秒钟执行一次
            _timer = new Timer(DoWork, 1, TimeSpan.Zero,
            TimeSpan.FromSeconds(3));
            return Task.CompletedTask;
        }
        /// <summary>
        /// 定时器具体执行的方法
        /// </summary>
        /// <param name="state"></param>
        private void DoWork(object state)
        {
            PostUserLoginDTO dto = new PostUserLoginDTO()
            {
                Login = "zhangsan",
                Pwd = "123",
            };
            userService.UserLogin(dto);
            Console.WriteLine($"{dto}");
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        public override void Dispose()
        {
            _timer?.Dispose(); //如果_timer对象不为null，则销毁
            base.Dispose();
        }
    }
}
